//
//  ELKeyChainManager.m
//  jobClient
//
//  Created by 一览ios on 2017/10/25.
//  Copyright © 2017年 YL1001. All rights reserved.
//

#import "ELKeyChainManager.h"

#import <UICKeyChainStore.h>

static NSString * const ELunloginUser = @"unloginUser";
static NSString * const ELloginIdentityAsEnterpriseKey = @"loginIdentityAsEnterprise";
static NSString * const ELloginIdentityTypeKey = @"loginIdentityType";
static NSString * const ELuserId = @"userId";

@interface ELKeyChainManager ()

@property (nonatomic, strong) UICKeyChainStore *keyChain;

@end

@implementation ELKeyChainManager

+ (ELKeyChainManager *)sharedManager {
    static id sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

#pragma mark - 当前用户id
- (NSString *)userId {
    NSString *userId = [self.keyChain stringForKey:ELuserId];
    return StringIsNotEmpty(userId) ? userId : ELunloginUser;
}

- (void)setUserId:(NSString *)userId {
    [self.keyChain setString:StringIsNotEmpty(userId) ? userId : ELunloginUser forKey:ELuserId];
}

#pragma mark - 当前用户上次登录身份
- (BOOL)loginIdentityAsEnterprise {
    return [[self keyChainValueForKey:ELloginIdentityAsEnterpriseKey] boolValue];
}

- (void)setLoginIdentityAsEnterprise:(BOOL)loginIdentityAsEnterprise {
    [self setKeyChainValue:loginIdentityAsEnterprise ? @"1" : @"0" forKey:ELloginIdentityAsEnterpriseKey];
}

- (ELLoginIdentityType)loginIdentityType {
    ELLoginIdentityType identityType = (ELLoginIdentityType)[[self keyChainValueForKey:ELloginIdentityTypeKey] integerValue];
//    if (identityType == ELLoginIdentityTypeBroker) {
//        [self setLoginIdentityType:ELLoginIdentityTypePerson];
//        identityType = ELLoginIdentityTypePerson;
//    }
    return identityType;
}

- (void)setLoginIdentityType:(ELLoginIdentityType)loginIdentityType {
    [self setKeyChainValue:@(loginIdentityType).stringValue forKey:ELloginIdentityTypeKey];
}

#pragma mark - 通用赋值、取值
- (NSString *)keyChainValueForKey:(NSString *)key {
    if (StringIsEmpty(key) || [key isEqualToString:ELunloginUser]) return nil;
    return [self.keyChain stringForKey:[NSString stringWithFormat:@"%@_%@",key,self.userId]];
}

- (void)setKeyChainValue:(NSString *)value forKey:(NSString *)key {
    if (![key isKindOfClass:[NSString class]] || ![value isKindOfClass:[NSString class]] || StringIsEmpty(key) || StringIsEmpty(value)) return;
    [self.keyChain setString:value forKey:[NSString stringWithFormat:@"%@_%@",key,self.userId]];
}


- (UICKeyChainStore *)keyChain {
    if (!_keyChain) {
        _keyChain = [UICKeyChainStore keyChainStoreWithService:ELBundleID];
    }
    return _keyChain;
}

@end
